//
//  Task ventilator - design 3
//  Binds PUSH socket to tcp://localhost:5557
//  Sends batch of tasks to workers via that socket
//
//  10000 tasks
//
package main

import (
	"fmt"
	"os"
	"zmq"
	"rand"
)

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()

	sender, err := context.Socket(zmq.PUSH)
	if err != nil {
		return err
	}
	defer sender.Close()

	err = sender.Bind("tcp://*:5557")
	if err != nil {
		return err
	}

	fmt.Printf("Press Enter when the workers are ready:")
	var buf [128]byte
	os.Stdin.Read(buf[:])
	fmt.Println("Sending tasks to workers...")

	// The first message is "0" and signals start of batch
	err = sender.Send([]byte("0:0"),0)
	if err != nil {
		return err
	}

	// Send 100 tasks
	task_nbr := 0
	total_msec := 0
	for task_nbr = 0; task_nbr < 10000; task_nbr++ {
		// Random workload from 1 to 1000msecs
		workload := rand.Intn(1000) + 1
		total_msec += workload
		data := fmt.Sprintf("%d:%d",task_nbr+1,workload)
		err = sender.Send([]byte(data),0)
		if err != nil {
			return err
		}
	}
	fmt.Printf("Total expected cost: %d mes\n", total_msec)
	zmq.Sleep(1)
	return nil
}

var errch = make(chan os.Error)

func main() {
	fmt.Println("Task ventilator")
	exit := make(chan bool)
	go func() {
		for {
			err := <-errch
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}()
	go func() {
		err := zmq_main()
		if err != nil {
			errch <- err
		} else {	
			exit <- true
		}
	}()
	<-exit
}
